local scene = director:createScene()

function scene:setUp(event)
    dbg.print("sceneGame:setUp")
	
	local allScaleX = 480/director.displayWidth
	local allScaleY = 320/director.displayHeight
	local dw = director.displayWidth
	local dh = director.displayHeight
	local startX = 90/allScaleX
	local startY = 70/allScaleY
	local x = startX
	local y = startY
	local angle = 0
	local ballMove = false
	local forceX = 0
	local forceY = 0
	local posBallX = x
	local posBallY = y
	local touchBall = false
	local score = 0
	local gameStats = "run"
	local gameTime = 0
	local lineCoordX = startX
	local lineCoordY = startY
	local angleLine = 0
	local paperBalls = 10
	
	system.debugTime = nil
	system.gameTime = 0
	system.timers = {}
	localTime = 0
		
	local ball = director:createSprite( { x=startX, y=startY, source="img/paperBall.png", xAnchor=0.5, yAnchor=0.5, zOrder=1,} )
	local basket = director:createSprite( { x=500, y=120, source="img/basketFront.png",	xAnchor=0.5, yAnchor=1, zOrder=2, xScale=.5/allScaleX, yScale=.5/allScaleY} )
	basket.x = dw-.5*basket.w/allScaleX
	basket.y = basket.h/2.5/allScaleY
	
	local slingshot = director:createSprite( { x=startX+20/allScaleX, y=startY, source="img/slingshot.png", xAnchor=0.5, yAnchor=1, zOrder=-1,} )
	local background = director:createSprite( { x=dw/2, y=dh/2, source="img/background.png", xAnchor=.5, yAnchor=.5, zOrder=-2,} )
	background.xScale = 1/allScaleX
	background.yScale = 1/allScaleY
	local line = director:createSprite( { x=slingshot.x-10/allScaleX, y=slingshot.y-5/allScaleY, source="img/line.png", xAnchor=1, yAnchor=.5, zOrder=0,} )
	local point = director:createSprite( { x=line.x, y=line.y, source="img/point.png", xAnchor=.5, yAnchor=.5, zOrder=0,} )
	local basketBack = director:createSprite( { x=basket.x, y=basket.y, source="img/basketBack.png",	xAnchor=0.5, yAnchor=.5, zOrder=0, xScale=.5/allScaleX, yScale=.5/allScaleY} )
	local lineLeft = director:createSprite( { x=basket.x-basket.w/2*.5/allScaleX, y=basket.y, source="img/lineLeft.png",	xAnchor=0, yAnchor=1, zOrder=3, isVisible=false} )
	local lineRight = director:createSprite( { x=basket.x+basket.w/2*.5/allScaleX, y=basket.y, source="img/lineRight.png",	xAnchor=1, yAnchor=1, zOrder=3, isVisible=false} )
	physics:setGravity(0, -25)
	physics:addNode(lineLeft, { type="static", isSensor=false } )
	physics:addNode(lineRight, { type="static", isSensor=false } )
	
	local labelTimeTitle = director:createLabel({x=10/allScaleX, y=290/allScaleY, hAlignment="left", color=color.red, text="Time: ", xScale=1/allScaleX, yScale=1/allScaleY})
	local labelTimeNumber = director:createLabel({x=80/allScaleX, y=290/allScaleY, hAlignment="left", color=color.red, text="", xScale=1/allScaleX, yScale=1/allScaleY})
	local labelPaperBallsTitle = director:createLabel({x=dw-210/allScaleX, y=290/allScaleY, hAlignment="left", color=color.red, text="Paper balls: ", xScale=1/allScaleX, yScale=1/allScaleY})
	local labelPaperBallsNumber = director:createLabel({x=dw-50/allScaleX, y=290/allScaleY, hAlignment="left", color=color.red, text="10", xScale=1/allScaleX, yScale=1/allScaleY})
	local boxLabels = director:createRectangle( { x=dw/2, y=dh/2, w=dw/2, h=dh/3, color=color.black, xAnchor=.5, yAnchor=.5, isVisible=false,} )
	local labelWinLose = director:createLabel({x=boxLabels.w/6, y=boxLabels.w/4.5, hAlignment="left", color=color.red, text="You lose", xScale=1.5/allScaleX, yScale=1.5/allScaleY, isVisible=false,})
	boxLabels:addChild(labelWinLose)
	local labelBestTime = director:createLabel({x=boxLabels.w/5, y=boxLabels.w/11, hAlignment="left", color=color.red, text="Try again", xScale=1.3/allScaleX, yScale=1.3/allScaleY, isVisible=false,})
	boxLabels:addChild(labelBestTime)
	
	local buttonRestart = director:createSprite(dw/2, -100, "img/button.png")
	buttonRestart.xAnchor=0.5; buttonRestart.yAnchor=0
	buttonRestart.xScale=.6/allScaleX; buttonRestart.yScale=.4/allScaleY; 
	buttonRestart.zOrder = 6
	buttonRestart.isVisible = false

	local labelRestart = director:createLabel(buttonRestart.w/2, buttonRestart.h/4, "Restart")
	labelRestart.xAnchor=0.5;
	labelRestart.hAlignment="center"
	labelRestart.xScale=1.1/allScaleX; labelRestart.yScale=1.3/allScaleY; 
	buttonRestart:addChild(labelRestart)
	
	
	
		function ballCollition(event)
			local target = event.target
			
			if event.phase == "began" then
				if (ball.x < lineLeft.x or ball.x < lineRight.x) then
					if (ball.y > lineLeft.y or ball.y > lineRight.y) then
						ball.physics:applyLinearImpulse(-1, 1)
					else
						ball.physics:applyLinearImpulse(-1, 0)
					end
				elseif (ball.x > lineLeft.x or ball.x > lineRight.x) then
					ball.physics:applyLinearImpulse(1, 1)
				end
			end
		end
		ball:addEventListener("collision", ballCollition)

		function ball:touch(event)
			if (event.phase == "began") then 
				posBallX = ball.x
				posBallY = ball.y
				touchBall = true
			end
		end
		ball:addEventListener("touch", ball)

		local onTouch = function(event)
			if (event.phase == "moved") then
				if (touchBall == true) then
					x = event.x
					y = event.y
					lineCoordX = event.x
					lineCoordY = event.y
					angle = math.atan((posBallX-x)/(posBallY-y))*180/math.pi
					ball.rotation = angle
					
					if (ballMove == false) then
						ball.x = x
						ball.y = y
						angleLine = math.atan((-y+line.y)/(-x+line.x))*180/math.pi
			   
						if (line.x < x) then
							angleLine = angleLine + 180
						end
						if (y>line.y) then
							lineScaleY = (y-line.y)/line.y*4/allScaleY
						else
							lineScaleY = (-y+line.y)/line.y*4/allScaleY
						end
						if (x>line.x) then
							lineScaleX = (x-line.x)/line.x*5.5/allScaleX
						else
							lineScaleX = (-x+line.x)/line.x*5.5/allScaleX
						end
						line.xScale = math.sqrt((lineScaleX^2)+(lineScaleY^2))
						line.rotation = 360-angleLine
					end
				end
			end
			if (event.phase == "ended") then 
				if (ballMove == false and touchBall == true) then
					ballMove = true
					physics:addNode(ball, { radius=ball.w/2, type="dynamic", isSensor=false } )
					forceX = (posBallX - x)*8
					forceY = (posBallY - y)*7
					ball.physics:applyForce (forceX, forceY, ball.x,ball.y)
					line.xScale = 1/allScaleX
					line.yScale = 1/allScaleY
				end
				touchBall = false
			end		
		end
		system:addEventListener("touch", onTouch)
		
		function system:getTime()
			if self.debugTime then
				return self.debugTime
			else
				return self.gameTime
			end
		end
		
	local ballUpdate = function ()
		
		gameTime = math.floor(system:getTime())
		labelTimeNumber.text = gameTime
		labelPaperBallsNumber.text = paperBalls
		
		if (gameStats == "new") then
			if  (paperBalls > 1 and paperBalls < 20) then
				paperBalls = paperBalls-1
				physics:removeNode(ball)
				ball.x = startX
				ball.y = startY
				x = startX
				y = startY
				posBallX = startX
				posBallY = startY
				ballMove = false			
				gameStats = "run"
			elseif (paperBalls == 99) then
				labelWinLose.text = "You Win"
				labelWinLose.isVisible = true
				labelBestTime.text = " "
				labelBestTime.isVisible = true
				boxLabels.isVisible = true
				buttonRestart.y = 0
				buttonRestart.isVisible = true
				
				file = io.open("scoreTime.txt")
				scoreTimeOne = tonumber(file:read())
				scoreTimeTwo = tonumber(file:read())
				scoreTimeThree = tonumber(file:read())
				file:close()
						
				if (gameTime < scoreTimeOne) then
					labelBestTime.text = "GREAT SCORE:"
					scoreTimeThree = scoreTimeTwo
					scoreTimeTwo = scoreTimeOne
					scoreTimeOne = gameTime
					elseif (gameTime < scoreTimeTwo) then
						labelBestTime.text = "GREAT SCORE:"
						scoreTimeThree = scoreTimeTwo
						scoreTimeTwo = gameTime
							elseif (gameTime < scoreTimeThree) then
							labelBestTime.text = "GREAT SCORE:"
							scoreTimeThree = gameTime
				end
				
				file = io.open("scoreTime.txt", "w")
				file:write(scoreTimeOne.."\n")
				file:write(scoreTimeTwo.."\n")
				file:write(scoreTimeThree.."\n")
				file:close()
			else
				--end game
				labelWinLose.text = "You Lose"
				labelWinLose.isVisible = true
				labelBestTime.text = "Try again"
				labelBestTime.isVisible = true
				boxLabels.isVisible = true
				buttonRestart.y = 0
				buttonRestart.isVisible = true
				paperBalls = 0
			end
		end
	
		if  (ballMove == true) then
			if (ball.y-ball.w/2 < 0) then
				if (gameStats == "run") then
					if (ball.x < lineRight.x and ball.x > lineLeft.x) then
						dbg.print("win")
						paperBalls = 99
						gameStats = "new"
					else
						dbg.print("lose")
						gameStats = "new"
					end
				end
			end
			if (ball.x>=dw) then
				dbg.print("lose")
				gameStats = "new"
			end
		end
	end
	system:addEventListener("update", ballUpdate)
	
	function buttonRestart:touch(event)
			if (event.phase == 'began') then
				
				paperBalls = 11
				system.debugTime = nil
				system.gameTime = 0
				system.timers = {}
				localTime = 0
				gameStats = "new"
				labelWinLose.isVisible = false
				labelBestTime.isVisible = false
				boxLabels.isVisible = false
				buttonRestart.isVisible = false
				
			end
		end
		buttonRestart:addEventListener('touch', buttonRestart)
		
end

function scene:tearDown(event)
	self:releaseResources();
    dbg.print("sceneGame:tearDown")
end

scene:addEventListener({"setUp", "tearDown"}, scene)
return scene